package cn.ocars.playgame.pencilstudy.ui.components

import android.content.Context
import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.opengl.Matrix
import android.view.MotionEvent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.input.motionprediction.MotionEventPredictor
import cn.ocars.playgame.pencilstudy.services.MiniCPMVRecognitionService
import cn.ocars.playgame.pencilstudy.ui.theme.PrimaryBlue
import cn.ocars.playgame.pencilstudy.ui.components.WritingRenderer
import cn.ocars.playgame.pencilstudy.model.Stroke
import cn.ocars.playgame.pencilstudy.model.StrokePoint
import kotlinx.coroutines.launch
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
import kotlin.math.sqrt

/**
 * MiniCPM-V 2.5模型书写卡片组件
 * 使用MiniCPM-V 2.5多模态模型进行书写笔迹评分
 */
@Composable
fun MultimodalGemmaWritingCard(
    key: Any, // 添加key参数
    character: String,
    expectedStrokeCount: Int,
    onWritingComplete: (MiniCPMVRecognitionService.RecognitionResult) -> Unit,
    modifier: Modifier = Modifier,
    onClearClick: (() -> Unit)? = null
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    
    // MiniCPM-V 2.5模型识别服务
    val recognitionService = remember { MiniCPMVRecognitionService(context) }
    
    // 初始化模型
    LaunchedEffect(Unit) {
        try {
            recognitionService.initialize()
        } catch (e: Exception) {
            println("MiniCPM-V 2.5模型初始化失败: ${e.message}")
        }
    }
    
    // 清理资源
    DisposableEffect(Unit) {
        onDispose {
            recognitionService.release()
        }
    }
    
    val renderer = remember(key) { // 使用key参数，确保字符或笔画数变化时重新创建renderer
        WritingRenderer(
            context = context,
            character = character,
            expectedStrokeCount = expectedStrokeCount,
            onWritingComplete = { userStrokes ->
                scope.launch {
                    try {
                        // 将StrokeData转换为Stroke
                        val convertedStrokes = userStrokes.map { strokeData ->
                            val points = mutableListOf<StrokePoint>()
                            // 将顶点数据转换为StrokePoint列表
                            for (i in strokeData.vertices.indices step 3) {
                                if (i + 1 < strokeData.vertices.size) {
                                    points.add(StrokePoint(strokeData.vertices[i], strokeData.vertices[i + 1]))
                                }
                            }
                            Stroke(points)
                        }
                        
                        val result = recognitionService.recognizeAndScore(
                            character = character,
                            strokes = convertedStrokes
                        )
                        onWritingComplete(result)
                    } catch (e: Exception) {
                        println("识别错误: ${e.message}")
                        // 返回默认结果
                        onWritingComplete(
                            MiniCPMVRecognitionService.RecognitionResult(
                                character = character,
                                totalScore = 0f,
                                confidence = 0f,
                                strokeScores = emptyList(),
                                feedback = "识别服务出错，请重试"
                            )
                        )
                    }
                }
            }
        )
    }
    
    Box(
        modifier = modifier.size(150.dp),
        contentAlignment = Alignment.Center
    ) {
        AndroidView(
            modifier = Modifier.fillMaxSize(),
            factory = {
                val glView = GLSurfaceView(context)
                glView.setEGLContextClientVersion(2)
                glView.preserveEGLContextOnPause = true
                glView.setRenderer(renderer)
                glView.renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
                
                glView.setOnTouchListener { view, event ->
                    renderer.handleTouchEvent(event, view.width, view.height)
                    true
                }
                
                renderer.setGLView(glView)
                glView
            }
        )
        
        // 橡皮图标
        IconButton(
            onClick = { 
                renderer.clear()
                onClearClick?.invoke()
            },
            modifier = Modifier
                .align(Alignment.TopEnd)
                .size(24.dp)
        ) {
            Icon(
                painter = painterResource(android.R.drawable.ic_menu_delete),
                contentDescription = "清除",
                tint = PrimaryBlue.copy(alpha = 0.7f),
                modifier = Modifier.size(16.dp)
            )
        }
        
        // 显示淡色字符提示
        Text(
            text = character,
            fontSize = 80.sp,
            fontWeight = FontWeight.Bold,
            color = PrimaryBlue.copy(alpha = 0.15f),
            textAlign = TextAlign.Center,
            modifier = Modifier.align(Alignment.Center)
        )
    }
}